<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="设备名称" prop="deviceName">
                <el-input
                        v-model="queryParams.deviceName"
                        placeholder="请输入设备名称"
                        clearable
                        @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item label="设备编号" prop="deviceId">
                <el-input
                        v-model="queryParams.deviceId"
                        placeholder="请输入设备编号"
                        clearable
                        @keyup.enter="handleQuery"
                />
            </el-form-item>

            <el-form-item label="安装位置" prop="location">
                <el-input
                        v-model="queryParams.location"
                        placeholder="请输入安装位置"
                        clearable
                        @keyup.enter="handleQuery"
                />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                        type="primary"
                        plain
                        icon="Plus"
                        @click="handleAdd"
                        v-hasPermi="['ar_check:device:add']"
                >新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="success"
                        plain
                        icon="Edit"
                        :disabled="single"
                        @click="handleUpdate"
                        v-hasPermi="['ar_check:device:edit']"
                >修改
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="danger"
                        plain
                        icon="Delete"
                        :disabled="multiple"
                        @click="handleDelete"
                        v-hasPermi="['ar_check:device:remove']"
                >删除
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="info" plain icon="Upload" @click="handleTeamImport"
                           v-hasPermi="['system:user:import']">
                    导入
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="warning"
                        plain
                        icon="Download"
                        @click="handleExport"
                        v-hasPermi="['ar_check:device:export']"
                >导出
                </el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="设备编号" align="center" prop="deviceId"/>
            <el-table-column label="设备名称" align="center" prop="deviceName"/>
            <el-table-column label="类型" align="center" prop="typeName"/>
            <el-table-column label="设备型号" align="center" prop="model"/>
            <el-table-column label="安装位置" align="center" prop="roomName"/>
            <el-table-column label="设备照片" align="center" prop="picture">
                <template #default="scope">
                    <image-preview :src="scope.row.picture" :width="50" :height="50"/>
                </template>
            </el-table-column>
            <el-table-column label="设备状态" align="center" prop="status">
                <template #default="{row}">
                    <dict-tag :options="device_status" :value="row.status"/>
                </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="notes"/>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                               v-hasPermi="['ar_check:device:edit']">修改
                    </el-button>
                    <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                               v-hasPermi="['ar_check:device:remove']">删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
                v-show="total>0"
                :total="total"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                @pagination="getList"
        />

        <!-- 添加或修改设备对话框 -->
        <el-dialog :title="title" v-model="open" width="800" append-to-body>
            <el-form inline ref="deviceRef" :model="form" :rules="rules" label-width="140px">
                <el-form-item label="设备名称" prop="deviceName">
                    <el-input v-model="form.deviceName" placeholder="请输入设备名称"/>
                </el-form-item>
                <el-form-item label="设备制造商" prop="manufacturer">
                    <el-input v-model="form.manufacturer" placeholder="请输入设备制造商"/>
                </el-form-item>
                <el-form-item label="设备型号" prop="model">
                    <el-input v-model="form.model" placeholder="请输入设备型号"/>
                </el-form-item>
                <el-form-item label="设备深度" prop="depthCm">
                    <el-input type="number" v-model.number="form.depthCm" placeholder="请输入设备深度"/>
                </el-form-item>
                <el-form-item label="设备宽度" prop="widthCm">
                    <el-input type="number" v-model.number="form.widthCm" placeholder="请输入设备宽度"/>
                </el-form-item>
                <el-form-item label="设备高度" prop="heightCm">
                    <el-input type="number" v-model.number="form.heightCm" placeholder="请输入设备高度"/>
                </el-form-item>
                <el-form-item label="设备重量" prop="weightKg">
                    <el-input type="number" v-model.number="form.weightKg" placeholder="请输入设备重量 kg"/>
                </el-form-item>
                <el-form-item label="采购人" prop="purchaserName">
                    <el-input v-model="form.purchaserName" placeholder="请输入采购人"/>
                </el-form-item>
                <el-form-item label="设备购买日期" prop="purchaseDate">
                    <el-date-picker clearable
                                    style="width: 10.4vw"
                                    v-model="form.purchaseDate"
                                    type="datetime"
                                    value-format="YYYY-MM-DD HH:mm:ss"
                                    placeholder="请选择设备购买日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="设备保修截止日期" prop="warrantyExpiryDate">
                    <el-date-picker clearable
                                    style="width: 10.4vw"
                                    v-model="form.warrantyExpiryDate"
                                    type="datetime"
                                    value-format="YYYY-MM-DD HH:mm:ss"
                                    placeholder="请选择设备保修截止日期">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="设备类型" prop="typeId">
                    <el-select style="width: 10.4vw" v-model="form.typeId" clearable placeholder="请选择设备类型">
                        <el-option v-for="item in typeList" :key="item.typeId" :label="item.typeName"
                                   :value="item.typeId"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="安装位置" prop="location">
                    <el-select style="width: 10.4vw" v-model="form.location" clearable placeholder="请选择设备类型">
                        <el-option v-for="item in dataCenter" :key="item.roomId" :label="item.roomName"
                                   :value="item.roomId"/>
                    </el-select>
                </el-form-item>
                <el-form-item label="备注" prop="notes">
                    <el-input v-model="form.notes" type="textarea" placeholder="请输入内容"/>
                </el-form-item>
                <el-form-item label="设备照片" prop="picture">
                    <image-upload v-model="form.picture"/>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>

        <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
            <el-upload :action="upload.url" ref="uploadRef" :limit="1" accept=".xlsx, .xls"
                       :on-progress="handleFileProgress"
                       :disabled="upload.isUploading" :auto-upload="false" drag
                       :headers="upload.headers" :on-success="handleFileSuccess">

                <el-icon class="el-icon--upload">
                    <UploadFilled/>
                </el-icon>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>

                <template #tip>
                    <div class="el-upload__tip text-center">
                        <span>仅允许导入xlsx格式文件。</span>
                        <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                                 @click="importTemplate">
                            下载模板
                        </el-link>
                    </div>
                </template>
            </el-upload>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitFileForm">确 定</el-button>
                    <el-button @click="upload.open = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { listDevice, getDevice, delDevice, addDevice, updateDevice } from '@/api/ar_check/device'
import { listTypeAll } from '@/api/ar_check/type.js'
import DictTag from '@/components/DictTag/index.vue'
import { UploadFilled } from '@element-plus/icons-vue'
import { getToken } from '@/utils/auth.js'
import { listCenterAll } from '@/api/ar_check/center.js'

defineOptions({
    name: 'Device'
})

const { proxy } = getCurrentInstance()
const { device_status } = proxy.useDict('device_status')

const deviceList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref('')
const typeList = ref([])
const dataCenter = ref([])

const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceName: null,
        typeId: null,
        location: null,
        manufacturer: null,
        model: null,
        depthCm: null,
        widthCm: null,
        heightCm: null,
        weightKg: null,
        picture: null,
        purchaseDate: null,
        warrantyExpiryDate: null,
        status: null,
        notes: null,
        purchaserName: null,
    },
    rules: {
        deviceName: [
            { required: true, message: '设备名称不能为空', trigger: 'blur' }
        ],
        typeId: [
            { required: true, message: '设备类型不能为空', trigger: 'blur' }
        ],
        manufacturer: [
            { required: true, message: '设备制造商不能为空', trigger: 'blur' }
        ],
        model: [
            { required: true, message: '设备型号不能为空', trigger: 'blur' }
        ],
        picture: [
            { required: true, message: '设备照片不能为空', trigger: 'blur' }
        ],
        purchaseDate: [
            { required: true, message: '设备购买日期不能为空', trigger: 'blur' }
        ],
        warrantyExpiryDate: [
            { required: true, message: '设备保修截止日期不能为空', trigger: 'blur' },
            { validator: validateWarrantyDate, trigger: 'blur' }
        ],
        purchaserName: [
            { required: true, message: '采购人不能为空', trigger: 'blur' }
        ],
        depthCm: [
            { type: 'number', message: '请输入有效的数字', trigger: 'blur' },
            { validator: validatePositiveNumber, trigger: 'blur' }
        ],
        widthCm: [
            { type: 'number', message: '请输入有效的数字', trigger: 'blur' },
            { validator: validatePositiveNumber, trigger: 'blur' }
        ],
        heightCm: [
            { type: 'number', message: '请输入有效的数字', trigger: 'blur' },
            { validator: validatePositiveNumber, trigger: 'blur' }
        ],
        weightKg: [
            { type: 'number', message: '请输入有效的数字', trigger: 'blur' },
            { validator: validatePositiveNumber, trigger: 'blur' }
        ]
    }
})

/*** 用户导入参数 */
const upload = ref({
    open: false,
    title: '设备导入',
    // 是否禁用上传
    isUploading: false,
    headers: { Authorization: 'Bearer ' + getToken() },
    url: import.meta.env.VITE_APP_BASE_API + '/ar_check/device/importData'
})

const { queryParams, form, rules } = toRefs(data)

/** 查询设备列表 */
function getList() {
    loading.value = true
    listDevice(queryParams.value).then(response => {
        deviceList.value = response.rows
        total.value = response.total
        loading.value = false
    })
}

// 取消按钮
function cancel() {
    open.value = false
    reset()
}


// 表单重置
function reset() {
    form.value = {
        deviceId: null,
        deviceName: null,
        typeId: null,
        location: null,
        picture: null,
        status: null,
        notes: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
    }
    proxy.resetForm('deviceRef')
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1
    getList()
}

/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm('queryRef')
    handleQuery()
}

/*校验数字*/
function validatePositiveNumber(rule, value, callback) {
    if (value !== null && value !== '' && value <= 0) {
        callback(new Error('请输入大于0的数字'))
    } else {
        callback()
    }
}

/*校验保修日期*/
function validateWarrantyDate(rule, value, callback) {
    const purchaseDate = form.value.purchaseDate // 获取购买日期
    const warrantyDate = value // 获取保修日期
    if (!purchaseDate) {
        callback(new Error('请先选择购买日期！'))
    }
    // 如果保修日期早于购买日期，则校验不通过
    if (purchaseDate && warrantyDate && warrantyDate < purchaseDate) {
        callback(new Error('保修截止日期不能早于购买日期'))
    } else {
        callback()
    }
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.deviceId)
    single.value = selection.length !== 1
    multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
    reset()
    getDeviceType()
    getDataCenter()
    open.value = true
    title.value = '添加设备'
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset()
    const _deviceId = row.deviceId || ids.value
    getDevice(_deviceId).then(response => {
        getDeviceType()
        getDataCenter()
        form.value = response.data
        open.value = true
        title.value = '修改设备'
    })
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs['deviceRef'].validate(valid => {
        if (valid) {
            if (form.value.deviceId != null) {
                updateDevice(form.value).then(response => {
                    proxy.$modal.msgSuccess('修改成功')
                    open.value = false
                    getList()
                })
            } else {
                console.log('xin')
                addDevice(form.value).then(response => {
                    proxy.$modal.msgSuccess('新增成功')
                    open.value = false
                    getList()
                })
            }
        }
    })
}

/** 删除按钮操作 */
function handleDelete(row) {
    const _deviceIds = row.deviceId || ids.value
    proxy.$modal.confirm('是否确认删除设备编号为"' + _deviceIds + '"的数据项？').then(function () {
        return delDevice(_deviceIds)
    }).then(() => {
        getList()
        proxy.$modal.msgSuccess('删除成功')
    }).catch(() => {
    })
}

/*查询所有类型*/
async function getDeviceType() {
    const { data } = await listTypeAll()
    typeList.value = data
}

/** 导出按钮操作 */
function handleExport() {
    proxy.download('ar_check/device/export', {
        ...queryParams.value
    }, `device_${new Date().getTime()}.xlsx`)
}

// 打开导入
function handleTeamImport() {
    upload.value.open = true
}

// 文件上传中
function handleFileProgress() {
    upload.value.isUploading = true
}

// 文件上传完成
function handleFileSuccess(response, file) {
    upload.value.open = false
    upload.value.isUploading = false
    proxy.$refs['uploadRef'].handleRemove(file)
    proxy.$alert('<div style=\'overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;\'>' +
        response.msg + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
    getList()
}

// 下载模板
function importTemplate() {
    proxy.download('ar_check/device/importTemplate', {}, `device_template_${new Date().getTime()}.xlsx`)
}

// 确定上传
async function submitFileForm() {
    proxy.$refs.uploadRef.submit()
}

// 查询机房
async function getDataCenter() {
    const { data } = await listCenterAll()
    dataCenter.value = data
}

getList()
</script>
